import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button } from 'antd';
import { useMemo, useRef, useState } from 'react';
// import { useRequest } from 'ahooks';
import { exportExcelServices, getSupervisionRecord } from '@/services/supervisionApi';
import { useModel, useRequest } from '@umijs/max';
import type { CascaderProps } from 'antd';
import dayjs from 'dayjs';
import React from 'react';
import ShowModelInfo from './components';
import ShowExportModelInfo from './components/exportModel';
import { leaderExportService } from './service';

interface Course {
  id: Number;
  classroomLocation: string;
}

interface Option {
  value: string | number;
  label: string;
  children?: Option[];
  disableCheckbox?: boolean;
}

export default function SupervisionCoursePage() {
  const [popVisible, setPopVisible] = React.useState(false);
  const [exportPopVisible, setExportPopVisible] = React.useState(false);
  const [detail, setDetail] = React.useState(null);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [selecttimeSlot, setSelecttimeSlot] = useState<any[]>([]);

  const onChange: CascaderProps<Option, 'value', true>['onChange'] = (value) => {
    setSelecttimeSlot(value);
  };

  // 自定义排序函数
  const customSorter = (a: Course, b: Course) => {
    // 提取房间号和前缀
    const extractRoomNumber = (location: string) => {
      const match = location.match(/([a-zA-Z]+)(\d+)/);
      if (match) {
        return { prefix: match[1], number: parseInt(match[2], 10) };
      }
      return { prefix: '', number: 0 };
    };

    const aRoom = extractRoomNumber(a.classroomLocation);
    const bRoom = extractRoomNumber(b.classroomLocation);

    // 首先按前缀排序
    if (aRoom.prefix !== bRoom.prefix) {
      return aRoom.prefix.localeCompare(bRoom.prefix);
    }

    // 如果前缀相同，按数字排序
    return aRoom.number - bRoom.number;
  };

  const exportService = useRequest(exportExcelServices, {
    manual: true,
    onSuccess: () => {
      (actionRef?.current as any)?.reload();
    },
  });

  const exportLeaderService = useRequest(leaderExportService, {
    manual: true,
    onSuccess: () => {
      (actionRef?.current as any)?.reload();
    },
  });

  const columns = useMemo<ProColumns[]>(
    () => [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        hideInSearch: true,
        width: 70,
        // 将文本颜色转换成蓝色
        render: (val) => <span style={{ color: '#1677ff', cursor: 'help' }}>{val}</span>,
      },
      {
        title: '所属组长',
        dataIndex: 'leaderName',
        hideInSearch: true,
        key: 'leaderName',
        width: 100,
      },
      {
        title: '督导人员',
        dataIndex: 'crewName',
        hideInSearch: true,
        key: 'crewName',
        width: 100,
      },
      {
        title: '上课地点',
        dataIndex: 'classroomLocation',
        key: 'classroomLocation',

        width: 200,
        sorter: customSorter,
      },
      {
        title: '开课课程',
        dataIndex: 'courseName',
        key: 'courseName',

        width: 200,
      },
      {
        title: '选择时间段',
        key: 'dateTimeRange',
        dataIndex: 'createdAtRange',
        valueType: 'dateTimeRange',
        hideInTable: true,
        search: {
          transform: (value: any) => {
            console.log('选择时间段 >>> ', value);
            return {
              startTime: dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss'),
              endTime: dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss'),
            };
          },
        },
      },
      {
        title: '上课班级',
        dataIndex: 'classNumber',
        key: 'classNumber',
        width: 320,
      },
      {
        title: '授课教师',
        dataIndex: 'instructor',
        key: 'instructor',
      },
      // {
      //     title: '拍摄照片',
      //     dataIndex: 'upload',
      //     key: 'selectCourse',
      //
      // },
      {
        dataIndex: 'createdAt',
        title: '创建时间',
        hideInSearch: true,
        width: 200,
        renderText: (val) => dayjs(val).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: '操作',
        valueType: 'option',
        key: 'option',
        render: (_: any, record: any) => [
          <Button
            type="link"
            size="middle"
            onClick={() => {
              setDetail({ ...record });
              setPopVisible(true);
            }}
          >
            详情
          </Button>,
        ],
      },
    ],
    [false],
  );

  const actionRef = useRef<ActionType>();

  return (
    <PageContainer title="督导记录">
      <ProTable
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        options={{ fullScreen: true, density: true, setting: true }}
        request={async (params) => {
          const res = await getSupervisionRecord(params);
          return {
            data: res.records,
            success: true,
            total: res.total,
          };
        }}
        toolBarRender={() => [
          currentUser && currentUser.role !== 'crew' ? (
            <Button
              onClick={() => {
                setExportPopVisible(true);
              }}
              type="primary"
            >
              导出
            </Button>
          ) : (
            <></>
          ),
        ]}
      />

      <ShowModelInfo
        data={detail}
        open={popVisible}
        onOpenChange={(_open: boolean) => {
          setPopVisible(_open);
          if (!_open) {
            setDetail(null);
          }
        }}
        onFinish={() => {
          setPopVisible(false);
          (actionRef?.current as any)?.reload();
        }}
      />

      {/* 教师 组长 导出记录 */}
      <ShowExportModelInfo
        role={currentUser?.role}
        open={exportPopVisible}
        onOpenChange={(_open: boolean) => {
          setExportPopVisible(_open);
        }}
        onFin={(value: Supervision.exportModel) => {
          console.log('导出窗口的数据', value);

          setExportPopVisible(false);
          if (value.role === 'teacher' && value.week) {
            // 教师导出
            exportService.run({ week: value.week });
          } else if (value.role === 'leader') {
            // 组长导出
            exportLeaderService.run(
              { dateTimeRange: value.dateTimeRange },
              value.fileName,
            );
          }
          (actionRef?.current as any)?.reload();
        }}
      />
    </PageContainer>
  );
}
